<template>
  <div>
        <van-address-list
      v-model="chosenAddressId"
      :list="list"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @select="onSelect"
    />
    <van-popup v-model="showEdit" position="bottom" :style="{ height: '75vh'}">
      <van-address-edit
        :area-list="areaList"
        show-delete
        show-set-default
        show-search-result
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        :address-info="currentList"
        @save="onSave"
        @delete="onDelete"
        @click-area="autoGet"
      />
    </van-popup>
  </div>
</template>

<script>
import areaList from "@/config/area.js";

import {
  getaddress,
  addAddress,
  getAddressList,
  deleteAddress
} from "@/request/api.js";
export default {
  data() {
    return {
      currentList: {},
      chosenAddressId: "1",
      areaList,
      showEdit: false,
      list: []
    };
  },
  methods: {
    onSelect(val){
      this.$store.commit('changeCurAddress',{obj:val,url:this.$route.path})
      this.$emit('changeState')
    },
    onAdd() {
      this.currentList = {};
      this.showEdit = true;
    },
    onEdit(item, index) {
      this.currentList = this.list[index];
      this.showEdit = true;
    },
    async getId(address, id) {
      let addressList = await this.autoGet(id);
      let myId = null;
      addressList.data.forEach(el => {
        let reg = new RegExp(`${el.name}`, "g");
        if (reg.test(address)) {
          // console.log(el.id)
          myId = el.id;
          return;
        }
      });
      return myId;
    },
    async onSave(val) {
      this.list.forEach(el => {
        if (el.id == val.id) {
          deleteAddress({
            id: val.id
          }).then(res => {

          })
          return
        }
      });
      // console.log(val);
      let {
        province,
        city,
        county,
        name,
        addressDetail: address,
        tel: mobile,
        isDefault: is_default
      } = val;
      let province_id = await this.getId(province, 1);
      let city_id = await this.getId(city, province_id);
      let district_id = await this.getId(county, city_id);
      let params = {
        address,
        mobile,
        is_default:this.list.length?is_default:true,
        name,
        province_id: province_id + "",
        district_id: district_id + "",
        city_id: city_id + ""
      };
      addAddress(params).then(res => {
        this.autoGetAddress();
        this.showEdit = false;
        this.$toast.success("成功");
      });
    },
    onDelete(val) {
      deleteAddress({
        id: val.id
      }).then(res => {
        this.autoGetAddress();
        if(val.id == this.chosenAddressId){
          this.$store.commit('changeCurAddress',{obj:{},url:this.$route.path})
        }
        this.$toast.success("删除成功");
        this.showEdit = false;
      });
    },
    autoGet(id) {
      return new Promise((resolve, reject) => {
        getaddress({
          params: {
            parentId: id || 1
          }
        }).then(res => {
          if (res.errno == "0") {
            resolve(res);
          } else {
            reject(res.errmsg);
          }
        });
      });
    },
    autoGetAddress() {
      getAddressList().then(res => {
        // console.log(res);
        if (res.data && res.data.length > 0) {
          this.list = res.data.reduce((prev, current) => {
            let {
              id,
              name,
              mobile: tel,
              district_name,
              address: addressDetail,
              is_default: isDefault
            } = current;
            let obj = {
              id,
              name,
              tel,
              addressDetail,
              isDefault: isDefault == 1 ? true : false
            };
            for (let key in this.areaList.county_list) {
              if (this.areaList.county_list[key] == district_name) {
                obj.areaCode = key;
                break;
              }
            }

            obj.address = current.full_region + current.address;
            prev.push(obj);
            return prev;
          }, []);
          let myDefault = this.list.filter(el => {
            return el.isDefault;
          });
          if (myDefault.length) {
            this.chosenAddressId = myDefault[0].id;
          }
          if(this.list.length == 1){
            let obj = this.list[0]
            if(obj.isDefault){

              this.$store.commit('changeCurAddress',{obj,url:this.$route.path})
            }
          }
        } else {
          this.list=[];
          this.$store.commit('changeCurAddress',{obj:{},url:this.$route.path})
        }
      });
    }
  },
  created() {
    this.autoGetAddress();
  }
};
</script>

<style>

</style>